// ValidationAspects
// Written by Mike Saunders
// Released under Microsoft Public License (Ms-PL)
using System.Collections.Generic;
using ValidationAspects.Sdk;

namespace ValidationAspects.Core
{
	internal class ValidatorCache<T> where T : class
	{
		private readonly Dictionary<T, IValidator> _validators = new Dictionary<T, IValidator>();
		private readonly Dictionary<T, IValidatorFactory[]> _factories = new Dictionary<T, IValidatorFactory[]>();

		public IValidator GetValidator(T key)
		{
			Enforce.IsNotNull(key, "key");
			IValidator validator;
			return _validators.TryGetValue(key, out validator) ? validator : null;
		}

		public void SetValidator(T key, IValidator validator)
		{
			Enforce.IsNotNull(key, "key");
			Enforce.IsNotNull(validator, "validator");
			_validators[key] = validator;
		}

		public IValidatorFactory[] GetFactories(T key)
		{
			Enforce.IsNotNull(key, "key");
			IValidatorFactory[] factories;
			return _factories.TryGetValue(key, out factories) ? factories : null;
		}

		public void SetFactories(T key, IValidatorFactory[] factories)
		{
			Enforce.IsNotNull(key, "key");
			Enforce.IsNotNull(factories, "factories");
			_factories[key] = factories;
			_validators.Remove(key);
		}

		public void Clear()
		{
			_factories.Clear();
			_validators.Clear();
		}

		public void Clear(T key)
		{
			Enforce.IsNotNull(key, "key");
			_factories.Remove(key);
			_validators.Remove(key);
		}
	}
}